package com.mvc.common.tools;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Http请求工具
 * @author JayEinstein
 */
public abstract class HttpUtil {

    /**
     * get请求封装
     * @param url
     * @param param
     * @return
     */
    public static Result get(String url, Map<String, Object> param) {

        UrlBuilder urlBuilder = UrlBuilder.of(url);

        for (Map.Entry<String, Object> entry : param.entrySet()) {
            urlBuilder.addQuery(entry.getKey(), entry.getValue());
        }

        // 创建
        HttpRequest httpRequest = HttpRequest.get(urlBuilder.build());

        try (HttpResponse response = httpRequest.execute()) {
            int status = response.getStatus();
            String res = response.body();

            return new Result(status, res);
        }

    }

    /**
     * post请求封装
     * @param url
     * @param body
     * @return
     */
    public static Result post(String url, Object body) {

        if (!(body instanceof String)) {
            body = JSON.toJSONString(body);
        }

        HttpRequest httpRequest = HttpRequest.post(url);
        httpRequest.body(String.valueOf(body));

        try (HttpResponse response = httpRequest.execute()) {
            int status = response.getStatus();
            String res = response.body();

            return new Result(status, res);
        }

    }



    /**
     * 返回结果封装
     */
    public static class Result {

        private int status = 500;

        private String response;

        public Result() {}

        public Result(int status, String response) {
            this.status = status;
            this.response = response;
        }

        /**
         * 接口调用是否成功
         * @return
         */
        public boolean isSuccess() {
            return status >= 200 && status < 300;
        }

        public int getStatus() {
            return status;
        }

        /**
         * 响应体
         * @return
         */
        public String getResponse() {
            if (isSuccess()) {
                return response;
            }
            throw new RuntimeException("接口调用异常");
        }

        public <T> T parseObject(Class<T> clz) {
            return JSON.parseObject(getResponse(), clz);
        }

        public <T> T parseObject(Type type) {
            return JSON.parseObject(getResponse(), type);
        }

        public <T> T parseObject(TypeReference<T> typeReference) {
            Type type = typeReference.getType();
            return JSON.parseObject(getResponse(), type);
        }

    }

}
